import React, { Component } from 'react';
import { Form, Input, Button } from 'element-react';
import { Link } from 'react-router-dom';
import { Message } from 'element-react';
import '../login/login.css';
import '../register/register.css';
//静态图片必须以此方法引入，并且资源文件夹只能在src下
import Background from '../../static/login_bg.jpg';
// 设置背景图片
const sectionStyle = {
  width: "100%",
  height: "100%",
  overflow: 'hidden',
  // makesure here is String确保这里是一个字符串，以下是es6写法
  backgroundImage: `url(${Background})`,
  backgroundRepeat: 'no-repeat',
  backgroundSize: 'cover',
};
export default class Register extends Component {
  // 数据层
  state = {
    statusSendCode: true,
    mount: 60,
    form: {
      phone: '',
      password: '',
      captcha: '',
      nickname: '',
    },
    rules: {
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入手机号'));
            } else if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(new Error('手机号码有误，请重填'));
            } else {
              callback();
            }
          }
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入密码'));
            } else {
              callback();
              console.log('验证通过')
            }
          }
        }
      ],
      captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入验证码'));
            } else {
              callback();
            }
          }
        }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入昵称'));
            } else {
              callback();
            }
          }
        }
      ],

    }
  };
  // 逻辑层
  // 提交表单
  handleSubmit(e) {
    e.preventDefault();
    this.refs.form.validate((valid) => {
      if (valid) {
        this.checkcaptChaverify();
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }
  // 检查是否注册过
  checkPhone() {
    let that = this;
    let { phone } = that.state.form;
    if (phone === '') {
      Message.error('请填写您的手机号码！');
    } else if (!(/^1[3456789]\d{9}$/.test(phone))) {
      Message.error('手机号码有误，请重填');
    } else {
      that.$post(that.$api.check, { phone: phone }).then(res => {
        console.log(res);
        if (res.code === 200) {
          // 未注册;
          if (res.exist === -1) {
            that.sendCode();
          } else {
            Message.error('您已经注册过了,请前往登录！');
          }
        } else {
          Message.error('错误')
        }
      });
    }
  }
  // 验证验证码
  checkcaptChaverify() {
    let that = this;
    let { phone, captcha } = that.state.form;
    that.$post(that.$api.captchaverify, { phone: phone, captcha: captcha }).then(res => {
      console.log(res);
      if (res.code === 200) {
        // 提交表单数据;
        that.register();
      } else {
        Message.error('错误');
      }
    });

  }
  // 注册
  register() {
    let that = this;
    let { form } = that.state;
    that.$post(that.$api.register, form).then(res => {
      console.log(res);
      if (res.code === 200) {
        Message.success('注册成功！');
        that.props.history.push("/login");
      } else {
        Message.error('错误');
      }
    });
  }

  onChange(key, value) {
    this.setState({
      form: Object.assign({}, this.state.form, { [key]: value }),
    });
  }
  // 发生验证码
  sendCode() {
    let timer;
    let that = this;
    let { mount } = this.state;
    let { phone } = this.state.form;
    //setState/props是异步的，取更新后的值在回调函数里取
    this.setState({
      statusSendCode: false,
    }, () => {
      // 发送验证码倒计时
      if (this.state.statusSendCode === false) {
        timer = setInterval(function () {
          mount--;
          if (mount <= 0) {
            clearInterval(timer);
            mount = 1;
            that.setState({
              statusSendCode: true,
            });
          }
          that.setState({
            mount: mount,
          });
        }, 1000);
        // 调发送验证码接口
        that.$post(that.$api.captchaSend, { phone: phone }).then(res => {
          console.log(res);
          if (res.code === 200) {
            // 未注册;
            Message.success('验证码发送成功！');
          } else {
            Message.error('错误')
          }
        });
      }
    });
  }
  //渲染层
  render() {
    const { form, rules, statusSendCode, mount } = this.state;
    return (
      <div style={sectionStyle}>
        <div className="user-wrap">

          <Form ref="form" model={form} rules={rules} labelWidth="0" className="demo-ruleForm">
            <h3>网易云音乐</h3>
            <Form.Item prop="phone">
              <Input value={form.phone} onChange={this.onChange.bind(this, 'phone')} autoComplete="off" placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item prop="captcha">
              <Input type="text" value={form.captcha} onChange={this.onChange.bind(this, 'captcha')} autoComplete="off" placeholder="请输入验证码" append={statusSendCode ?
                <Button className="send-code" type="primary" onClick={this.checkPhone.bind(this)} >发送验证码</Button> :
                <Button className="send-code" type="primary">{mount}s后重发</Button>
              } />
            </Form.Item>
            <Form.Item prop="password">
              <Input type="password" value={form.password} onChange={this.onChange.bind(this, 'password')} autoComplete="off" placeholder="请输入密码" />
            </Form.Item>
            <Form.Item prop="nickname">
              <Input value={form.nickname} onChange={this.onChange.bind(this, 'nickname')} autoComplete="off" placeholder="请输入昵称" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={this.handleSubmit.bind(this)}>注册</Button>
            </Form.Item>
            <Form.Item>
              <Link to="/login">已有账号？前往登录</Link >
            </Form.Item>
          </Form>

        </div>
      </div>
    );
  }
}